#!/usr/bin/env sh

# 获取提交消息
commit_message="$(cat "$1")"

# 定义正则表达式验证提交消息格式
# 格式: <type>(<scope>): <subject>
# 其中type可以是: feat, fix, docs, style, refactor, test, chore, build, ci, perf, revert
# 支持中文开头的subject
pattern="^(feat|fix|docs|style|refactor|test|chore|build|ci|perf|revert)(\([a-z0-9_-]+\))?: .{1,72}$"

# 验证提交消息
if ! echo "$commit_message" | grep -qE "$pattern"; then
  # 检测操作系统类型
  if [ -n "$WINDIR" ]; then
    # Windows环境下使用纯文本格式，避免ANSI颜色代码导致的乱码
    echo ""
    echo "[ERROR] 提交消息格式不符合规范 [ERROR]"
    echo ""
    echo "+------------------------------------------------------------+"
    echo "| 正确格式: <type>(<scope>): <subject>"
    echo "|"
    echo "| type选项: feat, fix, docs, style, refactor, test, chore, build, ci, perf, revert"
    echo "| scope: 可选，描述修改的范围"
    echo "| subject: 简短描述，首字母小写，不超过72个字符"
    echo "+------------------------------------------------------------+"
    echo ""
    echo "[OK] 示例: feat(login): 添加记住密码功能"
    echo ""
  else
    # 非Windows环境下使用美化的提示信息
    # 定义颜色和样式
    RED="\033[0;31m"
    GREEN="\033[0;32m"
    YELLOW="\033[0;33m"
    BOLD="\033[1m"
    RESET="\033[0m"
    
    # 定义符号
    ERROR_MARK="✗"
    OK_MARK="✓"
    BORDER_TOP_LEFT="┌"
    BORDER_TOP_RIGHT="┐"
    BORDER_BOTTOM_LEFT="└"
    BORDER_BOTTOM_RIGHT="┘"
    BORDER_HORIZONTAL="─"
    BORDER_VERTICAL="│"
    
    # 生成边框线
    BORDER_LINE=""
    for i in $(seq 1 60); do
      BORDER_LINE="${BORDER_LINE}${BORDER_HORIZONTAL}"
    done
    
    # 打印美化的错误信息
    echo ""
    echo "${RED}${BOLD}${ERROR_MARK} 提交消息格式不符合规范 ${ERROR_MARK}${RESET}"
    echo ""
    echo "${YELLOW}${BORDER_TOP_LEFT}${BORDER_LINE}${BORDER_TOP_RIGHT}${RESET}"
    echo "${YELLOW}${BORDER_VERTICAL}${RESET} ${BOLD}正确格式:${RESET} <type>(<scope>): <subject>"
    echo "${YELLOW}${BORDER_VERTICAL}${RESET}"
    echo "${YELLOW}${BORDER_VERTICAL}${RESET} ${BOLD}type选项:${RESET} feat, fix, docs, style, refactor, test, chore, build, ci, perf, revert"
    echo "${YELLOW}${BORDER_VERTICAL}${RESET} ${BOLD}scope:${RESET} 可选，描述修改的范围"
    echo "${YELLOW}${BORDER_VERTICAL}${RESET} ${BOLD}subject:${RESET} 简短描述，首字母小写，不超过72个字符"
    echo "${YELLOW}${BORDER_BOTTOM_LEFT}${BORDER_LINE}${BORDER_BOTTOM_RIGHT}${RESET}"
    echo ""
    echo "${GREEN}${BOLD}${OK_MARK} 示例:${RESET} feat(login): 添加记住密码功能"
    echo ""
  fi
  exit 1
fi